import {useEffect, useState} from "react";
import {Upload, UploadProps, message} from "antd";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import {baseUrl} from "@/api";

const path = {
    img: "/sys/file/upload", //图片上传
    excel: "/p/promotion/order/import", //淘宝推广订单信息导入 需提供xlsx格式文件
};

interface UploadFileProps extends UploadProps {
    url?: "img" | "excel";
    icon?: any;
    setImg?: (e?: any) => void;
}

function UploadFile({maxCount = 1, icon = "", className = "", url = "img", setImg}: UploadFileProps) {
    const [imageUrl, setImageUrl] = useState("");
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        setImg?.(imageUrl);
    }, [imageUrl, setImg]);

    const handleRemove = (e: any) => {
        console.log(e);
    };

    const handleChange = (info: any) => {
        if (info.file.status === "uploading") {
            setLoading(true);
            return;
        }
        // 当上传完毕
        if (info.file.status === "done") {
            setLoading(false);
            console.log(info.file);

            // 判断是否上传成功
            if (info.file.response.code === "OK") {
                // 把返回的图像地址设置给 imageUrl
                setImageUrl(info.file.response.data || true); // 取决于服务端返回的字段名
            }
        }
    };

    const handleBeforeUpload = (file: any) => {
        if (url === "img") {
            const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
            if (!isJpgOrPng) {
                message.error("只能上传 JPG/PNG 文件!");
            }
            const isLt1M = file.size / 1024 / 1024 < 10;
            if (!isLt1M) {
                message.error("图片不能超过10MB!");
            }
            return isJpgOrPng && isLt1M;
        } else if (url === "excel") {
            const isLt1M = file.size / 1024 / 1024 < 10;
            if (!isLt1M) {
                message.error("文件不能超过10MB!");
            }
            return isLt1M;
        }
    };

    const uploadButton = <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>;

    return (
        <Upload
            maxCount={maxCount}
            name="file"
            disabled={!!imageUrl}
            listType="picture-card"
            className={`${className} avatar-uploader`}
            showUploadList={false}
            action={`${baseUrl + path[url]}`}
            beforeUpload={handleBeforeUpload} // 上传前执行的操作
            onRemove={handleRemove}
            onChange={handleChange}
        >
            {icon || uploadButton}
        </Upload>
    );
}

export default UploadFile;
